import { onUnmounted, ref } from 'vue';

export function usePolling(callback, option) {
  let pollingTime = 10;
  let pollingLoop = true;
  let timerFn = null;
  const duration = ref(pollingTime);
  const status = ref(true);

  if (typeof option == 'number') {
    pollingTime = option;
  }

  if (typeof option == 'object') {
    const { time = 10, loop = true } = option;
    pollingTime = time;
    pollingLoop = loop;
  }

  const clear = () => {
    clearInterval(timerFn);
    timerFn = null;
    status.value = false;
  };

  const reset = () => {
    clear();
    duration.value = pollingTime;
    callback();
  };

  const run = () => {
    clear();
    duration.value = pollingTime;
    status.value = true;
    timerFn = setInterval(() => {
      duration.value = duration.value - 1;
      if (duration.value <= 0) {
        callback();
        pollingLoop ? run() : clear();
      }
    }, 1000);
  };

  onUnmounted(() => {
    clear();
  });

  return { duration, status, run, clear, reset };
}
